<?php

namespace api\modules\backend\controllers;

use api\modules\backend\models\MemberLevel;
use yii\data\Pagination;
use common\commands\Common;
use api\modules\backend\models\Member;
use Yii;
use yii\filters\auth\QueryParamAuth;

/**
 * Member Controller API
 *
 * @author Fong <xiaofeng.zhang@suppernovachina.com>
 */
class MemberController extends ControllerBase
{
    public $modelClass = 'api\modules\v1\models\Member';
    public $defaultAvatar = 'uploads/images/avatar.png';
    private $notDeleted = 0; //未删除状态
    private $memberLevelPaidStatus = 2; //会员升级已支付状态
    private $errorString; //错误信息

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => QueryParamAuth::className(),
            'optional' => [],
        ];
        $behaviors['authenticator']['except'] = ['options'];

        return $behaviors;
    }

    /**
     * 会员列表
     */
    public function actionIndex()
    {
        $time = time();
        $get = Yii::$app->request->get();

        $where = [
            'is_deleted' => $this->notDeleted
        ];
        $get['username'] = isset($get['username']) ? $get['username'] : '';
        $get['mobile'] = isset($get['mobile']) ? $get['mobile'] : '';
        $get['email'] = isset($get['email']) ? $get['email'] : '';
        $get['level'] = isset($get['level']) ? $get['level'] : '';
        if (isset($get['active']) && is_numeric($get['active'])) $where['m.active'] = $get['active'];

        $memberLevelModelClass = new MemberLevel();
        $memberLevelQuery = $memberLevelModelClass->filterQuery(true, $this->memberLevelPaidStatus, $time);

        $memberModelClass = new Member();
        $memberFields = array(
            'm.member_id',
            'username',
            'mobile',
            'email',
            'share_code',
            'm.active',
            'm.create_time',
            'm.update_time',
            'level' => 'IFNULL(`ml`.`level`, 0)'
        );
        $memberQuery = $memberModelClass::find()->from('{{%member}} as m')->select($memberFields)->where($where)
            ->leftJoin('{{%member_share_code}} as msc', 'msc.member_share_code_id = m.member_share_code_id')
            ->leftJoin('(' . $memberLevelQuery . ') as ml', 'ml.member_id = m.member_id')
            ->andwhere([
                'and',
                ['like', 'username', $get['username']],
                ['like', 'mobile', $get['mobile']],
                ['like', 'email', $get['email']]
            ]);

        if ($get['level'] !== '') {
            $memberQuery = $memberModelClass::find()->from('(' . $memberQuery->createCommand()->getRawSql() . ') as `member`')
                ->where(['`member`.`level`' => $get['level']]);
        }

        $countQuery = clone $memberQuery;
        $pages = new Pagination(['totalCount' => $countQuery->count()]);
        $member = $memberQuery->offset($pages->offset)
            ->limit($pages->limit)
            ->orderBy(['update_time' => SORT_DESC, 'create_time' => SORT_DESC])
            ->asArray()
            ->all();

        $meta = array('totalCount' => (int)$pages->totalCount, 'perPage' => $pages->getPageSize(), 'pageCount' => $pages->getPageCount(), 'currentPage' => $pages->getPage() + 1);
        $result = array('item' => $member, '_meta' => $meta);

        $this->success($result);
    }

    /**
     * 新增会员
     * @throws \yii\base\Exception
     * @throws \yii\db\Exception
     */
    public function actionCreate()
    {
        $time = time();
        $memberModelClass = new Member();
        $post = Yii::$app->request->post();

        if (mb_strlen($post['password']) < 6 || mb_strlen($post['password']) > 20) {
            $this->response(Common::getPackedResponse(DATABASE_FAILED, 'DATABASE_FAILED'));
        }

        if (!preg_match('/^(\w){4,20}$/', $post['password'])) {
            $this->response(Common::getPackedResponse(DATABASE_FAILED, 'DATABASE_FAILED'));
        }

        $memberModelClass->load($post, '');
        $memberModelClass->setPassword(md5($post['password']));

        $memberModelClass->real_name = $post['real_name'];
        $memberModelClass->avatar = $this->defaultAvatar;
        $memberModelClass->create_time = $time;
        $memberModelClass->update_time = $time;

        $tr = Yii::$app->db->beginTransaction();
        try {

            if (!$memberModelClass->setShareCode()) {
                throw new \Exception('DATABASE_FAILED');
            }

            if (!$memberModelClass->save()) {
                throw new \Exception('DATABASE_FAILED');
            }

            $tr->commit();

        } catch (\Exception $e) {
            $tr->rollBack();
            $this->response(Common::getPackedResponse(DATABASE_FAILED, Yii::t('app', $e->getMessage())));
        }

        $this->success(array('id' => (string)$memberModelClass->member_id));
    }

    /**
     * 会员详情
     */
    public function actionView()
    {
        $time = time();
        $get = Yii::$app->request->get();

        $member_id = is_numeric($get['id']) ? $get['id'] : 0;

        $memberLevelModelClass = new MemberLevel();
        $memberLevelQuery = $memberLevelModelClass->filterQuery(true, $this->memberLevelPaidStatus, $time);

        $memberModelClass = new Member();
        $memberFields = [
            '`m`.member_id',
            'username',
            'mobile',
            'level' => 'IFNULL(`ml`.`level`, 0)',
            '`msc`.`share_code`',
            'email',
            'real_name',
            'active'
        ];
        $member = $memberModelClass::find()->from('{{%member}} as m')->select($memberFields)
            ->leftJoin('{{%member_share_code}} as msc', 'msc.member_share_code_id = m.member_share_code_id')
            ->leftJoin('(' . $memberLevelQuery . ') as ml', 'ml.member_id = m.member_id')
            ->where(['`m`.`member_id`' => $member_id, 'is_deleted' => $this->notDeleted])
            ->asArray()
            ->one();

        $data = array('member' => $member);
        $this->success($data);
    }

    /**
     * 更新会员
     * @throws \yii\base\Exception
     * @throws \yii\db\Exception
     */
    public function actionUpdate()
    {
        $get = Yii::$app->request->get();
        $post = Yii::$app->request->post();

        unset($post['level']);
        unset($post['share_code']);

        $member_id = is_numeric($get['id']) ? $get['id'] : 0;

        if (empty($member_id)) {
            $this->errorString = Yii::t('app', '{attribute} does not exist!', ['attribute' => Yii::t('app', 'member_id')]);
            $this->response(Common::getPackedResponse(DATABASE_FAILED, $this->errorString));
        }

        $memberModelClass = new Member();
        $member = $memberModelClass::findOne(['member_id' => $member_id, 'is_deleted' => $this->notDeleted]);

        if (empty($member)) {
            $this->errorString = Yii::t('app', '{attribute} does not exist!', ['attribute' => Yii::t('app', 'member')]);
            $this->response(Common::getPackedResponse(DATABASE_FAILED, $this->errorString));
        }

        $member->setAttributes($post);
        $member->update_time = time();

        if (isset($post['password']) && !empty($post['password'])) {
            if (mb_strlen($post['password']) < 6 || mb_strlen($post['password']) > 20) {
                $this->response(Common::getPackedResponse(DATABASE_FAILED, 'DATABASE_FAILED1'));
            }

            if (!preg_match('/^(\w){4,20}$/', $post['password'])) {
                $this->response(Common::getPackedResponse(DATABASE_FAILED, 'DATABASE_FAILED1'));
            }

            $member->setPassword(md5($post['password']));
        }

        if (!$member->validate()) {//验证数据
            $this->response(Common::getPackedResponse(DATABASE_FAILED, 'DATABASE_FAILED'));
        }

        $tr = Yii::$app->db->beginTransaction();//事务 如果失败 就会滚数据
        try {
            if (!$member->update()) {
                throw new \Exception('DATABASE_FAILED');
            }

            $tr->commit();
        } catch (\Exception $e) {
            $tr->rollBack();
            $this->response(Common::getPackedResponse(DATABASE_FAILED, 'DATABASE_FAILED'));
        }

        $this->success(array('member_id' => $member_id));
    }

    /**
     * 删除会员
     * @throws \yii\db\Exception
     */
    public function actionDelete()
    {
        $get = Yii::$app->request->get();

        $member_id = is_numeric($get['id']) ? $get['id'] : 0;

        $memberModelClass = new Member();
        $member = $memberModelClass::findOne(['member_id' => $member_id, 'is_deleted' => $this->notDeleted]);

        if (empty($member)) {
            $this->response(Common::getPackedResponse(DATABASE_FAILED, 'DATABASE_FAILED'));
        }

        $member->is_deleted = 1;

        $tr = Yii::$app->db->beginTransaction();//事务 如果失败 就会滚数据
        try {
            if (!$member->update()) {
                throw new \Exception('DATABASE_FAILED');
            }

            $tr->commit();
        } catch (\Exception $e) {
            $tr->rollBack();
            $this->response(Common::getPackedResponse(DATABASE_FAILED, 'DATABASE_FAILED'));
        }

        $this->success(array('member_id' => $member_id));
    }
}